<template>
  <aside class="sidebar" :class="{ collapsed: isCollapsed, 'mobile-hidden': isMobileHidden }">
    <!-- 侧边栏头部 -->
    <div class="sidebar-header">
      <div class="logo-section" v-if="!isCollapsed">
        <div class="logo">
          <span class="logo-icon">🤖</span>
          <span class="logo-text">AI Chat</span>
        </div>
      </div>
      
      <!-- 折叠按钮 -->
      <el-button
        class="collapse-btn"
        :icon="isCollapsed ? 'Expand' : 'Fold'"
        circle
        size="small"
        @click="toggleCollapse"
      />
    </div>

    <!-- 🔥 新增：模式切换区域 -->
    <div class="mode-section" v-if="!isCollapsed">
      <div class="mode-switcher">
        <el-segmented 
          v-model="chatMode" 
          :options="modeOptions"
          size="small"
          @change="handleModeChange"
        />
      </div>
    </div>

    <!-- 新建对话按钮 -->
    <div class="new-chat-section" v-if="!isCollapsed">
      <el-button
        type="primary"
        class="new-chat-btn"
        @click="onNewSession"
        :icon="'Plus'"
        size="default"
        :disabled="isLoadingSessions"
      >
        {{ getNewChatButtonText() }}
      </el-button>
    </div>
    
    <div class="new-chat-section" v-else>
      <el-tooltip :content="getNewChatButtonText()" placement="right">
        <el-button
          type="primary"
          class="new-chat-btn-collapsed"
          @click="onNewSession"
          :icon="chatMode === 'text' ? 'ChatDotRound' : 'Picture'"
          circle
          :disabled="isLoadingSessions"
        />
      </el-tooltip>
    </div>

    <!-- 会话列表 -->
    <div class="sessions-container">
      <div v-if="isLoadingSessions" class="sessions-loading-indicator">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>正在加载会话...</span>
      </div>
      <SessionList
        v-else
        :sessions="sessions"
        :active-session="activeSession"
        :active-session-id="activeSessionId"
        :is-collapsed="isCollapsed"
        :chat-mode="chatMode"
        :is-loading-sessions="isLoadingSessions"
        @select="onSelectSession"
        @new="onNewSession"
      />
      <!-- 可以考虑在 SessionList 内部处理空状态，或者在这里处理 -->
      <div v-if="!isLoadingSessions && sessions.length === 0" class="no-sessions-found">
        <p>暂无会话，请点击“新建对话”开始。</p>
      </div>
    </div>

    <!-- 侧边栏底部 -->
    <div class="sidebar-footer" v-if="!isCollapsed">
      <div class="user-info">
        <el-avatar :size="28" src="https://api.dicebear.com/7.x/avataaars/svg?seed=User" />
        <span class="username">用户</span>
      </div>
      <el-dropdown trigger="click">
        <el-button :icon="'Setting'" circle size="small" />
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>设置</el-dropdown-item>
            <el-dropdown-item divided>退出登录</el-dropdown-item>
          </el-dropdown-Menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 移动端遮罩层 -->
    <div
      class="mobile-overlay"
      v-if="!isMobileHidden && isMobile"
      @click="hideMobileSidebar"
    ></div>
  </aside>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import SessionList from '@/components/SessionList.vue'
import { Loading } from '@element-plus/icons-vue' // 引入 Loading 图标

const props = defineProps({
  sessions: {
    type: Array,
    default: () => []
  },
  activeSession: {
    type: Object,
    default: () => ({})
  },
  activeSessionId: {
    type: [String, Number],
    default: null
  },
  isLoadingSessions: { // 🔥 新增：会话列表加载状态
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['select', 'new', 'toggle-collapse', 'mode-change'])

// 响应式状态
const isCollapsed = ref(false)
const isMobile = ref(false)
const isMobileHidden = ref(true)

// 🔥 新增：聊天模式状态
const chatMode = ref(localStorage.getItem('chat-mode') || 'text')

// 🔥 模式选项
const modeOptions = ref([
  { 
    label: '文本', 
    value: 'text'
  },
  { 
    label: '图像', 
    value: 'multimodal'
  }
])

// 检测移动端
function checkIsMobile() {
  isMobile.value = window.innerWidth <= 768
  // 在非移动端模式下，确保侧边栏不是“隐藏”的
  if (!isMobile.value) {
    isMobileHidden.value = false
  }
}

// 🔥 获取新建按钮文本
function getNewChatButtonText() {
  return chatMode.value === 'text' ? '新建文本对话' : '新建图像对话'
}

// 🔥 处理模式切换
function handleModeChange(mode) {
  chatMode.value = mode
  localStorage.setItem('chat-mode', mode)
  console.log('侧边栏模式切换:', mode)
  emit('mode-change', mode)
  // 模式切换后，最好重置到新的空会话状态
  emit('new', { mode: chatMode.value })
}

// 折叠/展开侧边栏
function toggleCollapse() {
  if (isMobile.value) {
    isMobileHidden.value = !isMobileHidden.value
  } else {
    isCollapsed.value = !isCollapsed.value
  }
  emit('toggle-collapse', { collapsed: isCollapsed.value, mobileHidden: isMobileHidden.value })
}

// 显示移动端侧边栏
function showMobileSidebar() {
  if (isMobile.value) {
    isMobileHidden.value = false
  }
}

// 隐藏移动端侧边栏
function hideMobileSidebar() {
  if (isMobile.value) {
    isMobileHidden.value = true
  }
}

// 选择会话
function onSelectSession(session) {
  emit('select', session)
  // 移动端选择后自动隐藏侧边栏
  if (isMobile.value) {
    hideMobileSidebar()
  }
}

// 新建会话
function onNewSession() {
  // 🔥 新建会话时传递当前模式
  emit('new', { mode: chatMode.value })
  // 移动端新建后自动隐藏侧边栏
  if (isMobile.value) {
    hideMobileSidebar()
  }
}

// 监听窗口大小变化
function handleResize() {
  checkIsMobile()
}

// 暴露方法给父组件
defineExpose({
  showMobileSidebar,
  hideMobileSidebar,
  toggleCollapse
})

onMounted(() => {
  checkIsMobile()
  window.addEventListener('resize', handleResize)
  
  // 恢复保存的模式
  const savedMode = localStorage.getItem('chat-mode')
  if (savedMode && ['text', 'multimodal'].includes(savedMode)) {
    chatMode.value = savedMode
  }
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped>
.sidebar {
  width: 280px;
  background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
  border-right: 1px solid #e2e8f0;
  box-shadow: 4px 0 20px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  z-index: 1000;
}

.sidebar.collapsed {
  width: 60px;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #f1f5f9;
  background: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  position: sticky;
  top: 0;
  z-index: 10;
}

.logo-section {
  flex: 1;
  overflow: hidden;
}

.logo {
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 700;
  color: #1e293b;
}

.logo-icon {
  font-size: 24px;
  animation: float 3s ease-in-out infinite;
}

@keyframes float {
  0%, 100% { transform: translateY(0px); }
  50% { transform: translateY(-3px); }
}

.logo-text {
  font-size: 18px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.collapse-btn {
  flex-shrink: 0;
  border: 1px solid #e2e8f0;
  background: #ffffff;
  transition: all 0.3s ease;
}

.collapse-btn:hover {
  background: #f8fafc;
  transform: scale(1.05);
}

.mode-section {
  padding: 12px 20px;
  border-bottom: 1px solid #f1f5f9;
  background: rgba(248, 250, 252, 0.5);
}

.mode-switcher {
  width: 100%;
}

.mode-switcher :deep(.el-segmented) {
  width: 100%;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 10px;
  padding: 2px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  border: 1px solid #e2e8f0;
}

.mode-switcher :deep(.el-segmented__item) {
  flex: 1;
  font-size: 13px;
  font-weight: 500;
  padding: 8px 12px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.mode-switcher :deep(.el-segmented__item.is-selected) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
}

.mode-switcher :deep(.el-segmented__item:hover:not(.is-selected)) {
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
}

.new-chat-section {
  padding: 16px 20px;
  border-bottom: 1px solid #f1f5f9;
}

.new-chat-btn {
  width: 100%;
  height: 44px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
  white-space: nowrap;
}

.new-chat-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.new-chat-btn-collapsed {
  width: 100%;
  height: 44px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
  position: relative;
  transition: all 0.3s ease;
}

.new-chat-btn-collapsed:hover {
  transform: translateY(-1px);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
}

.sessions-container {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
  position: relative; /* 用于定位加载指示器和空状态提示 */
  
  /* 美化滚动条 */
  scrollbar-width: thin;
  scrollbar-color: rgba(148, 163, 184, 0.3) transparent;
}

.sessions-container::-webkit-scrollbar {
  width: 4px;
}

.sessions-container::-webkit-scrollbar-track {
  background: transparent;
}

.sessions-container::-webkit-scrollbar-thumb {
  background: rgba(148, 163, 184, 0.3);
  border-radius: 2px;
}

.sessions-container::-webkit-scrollbar-thumb:hover {
  background: rgba(148, 163, 184, 0.5);
}

.sessions-loading-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #667eea;
  font-size: 14px;
  gap: 8px;
}

.sessions-loading-indicator .el-icon {
  animation: rotate 1.5s linear infinite; /* 加载图标旋转动画 */
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.no-sessions-found {
  padding: 20px;
  text-align: center;
  color: #888;
  font-size: 14px;
}

.sidebar-footer {
  padding: 16px 20px;
  border-top: 1px solid #f1f5f9;
  background: rgba(248, 250, 252, 0.8);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  font-size: 14px;
  font-weight: 500;
  color: #475569;
}

/* 移动端样式 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh;
    width: 280px;
    z-index: 1000;
    transform: translateX(0); /* 默认显示 */
  }
  
  .sidebar.mobile-hidden {
    transform: translateX(-100%); /* 隐藏时移出屏幕 */
  }
  
  .mobile-overlay {
    position: fixed;
    top: 0;
    left: 0; /* 覆盖整个屏幕 */
    width: 100%; /* 覆盖整个屏幕 */
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999; /* 低于侧边栏 (1000)，高于主内容 */
    transition: opacity 0.3s ease; /* 淡入淡出效果 */
  }
  
  .collapse-btn {
    display: none; /* 移动端折叠按钮由父组件的移动菜单按钮替代 */
  }
  
  .mode-section {
    padding: 10px 16px;
  }
  
  .mode-switcher :deep(.el-segmented__item) {
    font-size: 12px;
    padding: 6px 8px;
  }
}

/* 折叠状态下的特殊样式 */
.collapsed .sidebar-header {
  padding: 16px 8px;
  justify-content: center;
}

.collapsed .new-chat-section {
  padding: 16px 8px;
}

.collapsed .sidebar-footer {
  padding: 16px 8px;
  justify-content: center;
}

.collapsed .user-info {
  display: none;
}

.collapsed .mode-section {
  display: none; /* 折叠时隐藏模式切换器 */
}

/* 动画效果 */
.sidebar * {
  transition: all 0.3s ease;
}
</style>
